<template>
  <transition name="fade">
    <div v-if="showNotification" class="connection-status" :class="notificationType">
      <div class="status-content">
        <div class="status-icon">
          <i :class="iconClass"></i>
        </div>
        <div class="status-text">
          <h4>{{ notificationTitle }}</h4>
          <p>{{ notificationMessage }}</p>
        </div>
        <button v-if="canRetry" class="retry-btn" @click="handleRetry">
          <i class="el-icon-refresh"></i>
          重试
        </button>
        <button class="close-btn" @click="closeNotification">
          <i class="el-icon-close"></i>
        </button>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import { testConnection } from '../api/request'

const userStore = useUserStore()

// 状态管理
const showNotification = ref(false)
const notificationType = ref('info') // info, warning, error, success
const notificationTitle = ref('')
const notificationMessage = ref('')
const canRetry = ref(false)
const lastCheckTime = ref(0)

// 图标映射
const iconClass = computed(() => {
  const iconMap = {
    info: 'el-icon-info',
    warning: 'el-icon-warning',
    error: 'el-icon-circle-close',
    success: 'el-icon-circle-check'
  }
  return iconMap[notificationType.value] || 'el-icon-info'
})

// 检查间隔（毫秒）
const CHECK_INTERVAL = 30000 // 30秒检查一次
const DEBOUNCE_DELAY = 5000 // 5秒内不重复提示

let checkInterval = null

// 检查服务器连接
const checkServerConnection = async () => {
  const now = Date.now()
  if (now - lastCheckTime.value < DEBOUNCE_DELAY) {
    return // 避免频繁检查
  }

  lastCheckTime.value = now

  try {
    const isConnected = await testConnection()
    if (!isConnected) {
      showConnectionError('无法连接到服务器', '请检查网络连接或稍后重试', true)
    } else {
      // 如果之前显示的是连接错误，现在可以关闭
      if (notificationType.value === 'error' && notificationMessage.value.includes('连接')) {
        closeNotification()
      }
    }
  } catch (error) {
    console.warn('连接检查失败:', error.message)
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  if (!userStore.isLoggedIn && userStore.userInfo) {
    // 有用户信息但未登录，可能是token过期
    showAuthWarning('登录状态已过期', '请重新登录以继续使用完整功能', true)
  }
}

// 显示连接错误
const showConnectionError = (title, message, retry = false) => {
  notificationType.value = 'error'
  notificationTitle.value = title
  notificationMessage.value = message
  canRetry.value = retry
  showNotification.value = true

  // 5秒后自动关闭
  setTimeout(() => {
    if (showNotification.value) {
      showNotification.value = false
    }
  }, 5000)
}

// 显示认证警告
const showAuthWarning = (title, message, showLogin = false) => {
  notificationType.value = 'warning'
  notificationTitle.value = title
  notificationMessage.value = message
  canRetry.value = false
  showNotification.value = true

  // 3秒后自动关闭
  setTimeout(() => {
    if (showNotification.value) {
      showNotification.value = false
    }
  }, 3000)
}

// 显示成功提示
const showSuccess = (title, message) => {
  notificationType.value = 'success'
  notificationTitle.value = title
  notificationMessage.value = message
  canRetry.value = false
  showNotification.value = true

  // 2秒后自动关闭
  setTimeout(() => {
    if (showNotification.value) {
      showNotification.value = false
    }
  }, 2000)
}

// 重试连接
const handleRetry = async () => {
  canRetry.value = false
  await checkServerConnection()
}

// 关闭通知
const closeNotification = () => {
  showNotification.value = false
}

// 监听网络状态变化
const handleNetworkChange = () => {
  if (navigator.onLine) {
    // 网络恢复，重新检查连接
    setTimeout(checkServerConnection, 1000)
  } else {
    showConnectionError('网络连接已断开', '请检查您的网络连接', false)
  }
}

// 监听API错误事件
const handleApiError = (event) => {
  const { type, message, code } = event.detail
  
  switch (code) {
    case 401:
    case 403:
      showAuthWarning('需要登录', '请先登录以继续使用')
      break
    case 404:
      // 404错误静默处理，通常是资源不存在
      break
    case 500:
      showConnectionError('服务器内部错误', '服务器遇到了一些问题，请稍后再试', true)
      break
    case 'NETWORK_ERROR':
    case 'ECONNREFUSED':
      showConnectionError('网络连接失败', '无法连接到服务器，请检查网络', true)
      break
    default:
      if (type === 'connection') {
        showConnectionError('连接失败', message || '网络连接出现问题', true)
      }
  }
}

// 初始化
onMounted(() => {
  // 监听网络状态变化
  window.addEventListener('online', handleNetworkChange)
  window.addEventListener('offline', handleNetworkChange)
  
  // 监听自定义API错误事件
  window.addEventListener('api-error', handleApiError)
  
  // 定期检查连接状态
  checkInterval = setInterval(checkServerConnection, CHECK_INTERVAL)
  
  // 首次检查
  setTimeout(() => {
    checkServerConnection()
    checkLoginStatus()
  }, 1000)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('online', handleNetworkChange)
  window.removeEventListener('offline', handleNetworkChange)
  window.removeEventListener('api-error', handleApiError)
  
  if (checkInterval) {
    clearInterval(checkInterval)
  }
})

// 暴露方法供外部调用
const connectionStatus = {
  showConnectionError,
  showAuthWarning,
  showSuccess,
  closeNotification
}

// 将方法挂载到全局
window.$connectionStatus = connectionStatus
</script>

<style scoped>
.connection-status {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 9999;
  min-width: 320px;
  max-width: 400px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.connection-status.info {
  background: rgba(64, 158, 255, 0.95);
  border-left: 4px solid #409eff;
}

.connection-status.warning {
  background: rgba(230, 162, 60, 0.95);
  border-left: 4px solid #e6a23c;
}

.connection-status.error {
  background: rgba(245, 108, 108, 0.95);
  border-left: 4px solid #f56c6c;
}

.connection-status.success {
  background: rgba(103, 194, 58, 0.95);
  border-left: 4px solid #67c23a;
}

.status-content {
  display: flex;
  align-items: center;
  padding: 16px;
  gap: 12px;
}

.status-icon {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  color: white;
  font-size: 14px;
}

.status-text {
  flex: 1;
  min-width: 0;
}

.status-text h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: white;
}

.status-text p {
  margin: 0;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.4;
}

.retry-btn {
  flex-shrink: 0;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.retry-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.close-btn {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  background: none;
  border: none;
  color: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-btn:hover {
  color: white;
  transform: scale(1.1);
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.fade-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .connection-status {
    left: 10px;
    right: 10px;
    top: 10px;
    min-width: auto;
  }
  
  .status-content {
    padding: 12px;
    gap: 8px;
  }
  
  .status-text h4 {
    font-size: 13px;
  }
  
  .status-text p {
    font-size: 11px;
  }
}
</style>